package test.functionQuery.functionsort;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.FloatDocValues;
import com.alibaba.fastjson.JSON;
import com.hunteron.bean.StringCountHO;
import com.hunteron.common4s.jdk.string.str.StringTools;

/**
 * Created by chenbingwen on 18/1/19.
 */
public class CompanyFunctionSortValueSource extends ValueSource {

    public String functionName;
    public ValueSource field;

    public CompanyFunctionSortValueSource(String functionName, ValueSource field) {
        super();
        this.functionName = functionName;
        this.field = field;
    }

    @Override
    public FunctionValues getValues(@SuppressWarnings("rawtypes") Map context, AtomicReaderContext readerContext) throws IOException {
        final FunctionValues fieldVals = field.getValues(context, readerContext);
        return new FloatDocValues(this) {
            @Override
            public float floatVal(int doc) {
                String fieldValues = fieldVals.strVal(doc);
                return functionSortValueWithString(fieldValues, functionName);
            }

            @Override
            public String toString(int doc) {
                return description() + " : " + functionName;
            }
        };
    }

    public float functionSortValueWithString(String fieldValue, String functionNames) {
        if (StringUtils.isBlank(fieldValue)) {
            return 0f;
        }
        String[] values = functionNames.split("\\s+");
        float total = 0;
        for (String v : values) {
            total += functionSortValue(fieldValue, v);
        }
        System.out.println("score:" + total);
        return total;
    }

    public float functionSortValue(String fieldValue, String functionName) {
        // functionName = key
        List<StringCountHO> data = JSON.parseArray(fieldValue, StringCountHO.class);
        if (CollectionUtils.isEmpty(data)) {
            return 0;
        }
        List<String> ids = StringTools.stringToStringList(functionName);
        if (CollectionUtils.isEmpty(ids)) {
            return 0;
        }
        double score = 0;
        for (String id : ids) {
            for (StringCountHO tmp : data) {
                if (StringUtils.equals(id, tmp.getCode())) {
                    score += tmp.getPercent();
                    break;
                }
            }
        }
        return (float) score;
    }

    @Override
    public boolean equals(Object o) {
        return false;
    }

    @Override
    public int hashCode() {
        return 0;
    }

    @Override
    public String description() {
        return "companyFunctionSort";
    }

}
